# encoding=utf-8
'''
Created on 2012-12-30

@author: Administrator
'''

from actionModule.handle import base
from base.common import createBaseHtml, getQueryHtml, retSuccess, retHtml, \
    renderNoescape, renderField, render, toDict, execMysql
from base.dbCommon import getPage, getLimit, convertToArray
from config.db.models import Html, JsonLog
from config.settings import PROJECT_PATH
import datetime
import json
import random
import os

cfg={
   'root':'yqy',
   'pageTitle':'首页',
   'my_config':{
            'debug':True
        }
   }
formJson = [
          {'id':'id', 'key':'Hidden', 'name':'主键'},
          {'id':'name', 'key':'RelaInput', 'name':'名称', 'noNull':True,'keyup':'fillRela'},
          {'id':'copyId', 'key':'Field', 'version':'2.0','name':'拷贝表单','fieldType':'single','action':'htmlHandle'},
          {'id':'path', 'key':'Input', 'name':'路径', 'noNull':True},
          {'id':'type', 'key':'Select', 'name':'类型', 'noNull':True,'subs':[{'id':'html','text':'html'},{'id':'text','text':'text'}]},
          {'id':'remark', 'key':'Input', 'name':'备注', 'noNull':True},
          {'id':'rightId', 'key':'Input', 'name':'权限ID', 'noNull':True},
          {'id':'formId', 'key':'Input', 'name':'表单ID','noNull':True},
          {'key':'Submit', 'action':'htmlHandle.create','back':'closeTab'},
          {'key':'Script'},
         ]

filePath=PROJECT_PATH+"/yqy/html/templates/common/"
htmlPath=PROJECT_PATH+"/yqy/html/module/"
formPath=PROJECT_PATH+"/yqy/form/"
        

def saveText(item):
    formFile=open(formPath+item.formId+".json","rb")
    str=formFile.read()
    formJson=json.loads(str)
    htmlArr=[]
    validArr={}
    #text情况不处理head
    for field in formJson['rows']:
        addValid(validArr,field['param'])
        if field.has_key('childs'):
            field['param']['content']=getChild(validArr,field['childs'])
            htmlArr.append(renderNoescape("common/"+field['fieldType']+".html",field['param']))
        else:
            htmlArr.append(getHtml("common/"+field['fieldType']+".html",field['param']))
    
    jsFile=open(formPath+"js/"+item.name+"_valid.js","wb")
    jsFile.write("var %s_valid=%s"%(item.name,json.dumps(validArr)))  
    jsFile.close()
          
    htmlFile=open(formPath+"html/"+item.name+".html","wb")
    htmlFile.write("".join(htmlArr))
    htmlFile.close()
    formFile.close()
    return retSuccess("创建成功")


class htmlHandle(base):
          
    def __init__(self):
        self.formJson=formJson
        
    def create(self):
        item = self.table()
        for temp in self.request.params:
            item.setAttr(temp, self.request.params.get(temp))
        
        #添加表单 执行表单复制  编辑不处理
        if not item.id and item.copyId:
            newFile=open('%s/%s.json'%(formPath,item.formId),"wb")
            fromFile=open('%s/%s.json'%(formPath,item.copyId),"rb")
            newFile.write(fromFile.read())
            fromFile.close()
            newFile.close()
            
        #编辑需判断是否改表单名称
        if item.id:
            old=self.table.objects.get(id=item.id)
            if not old['formId']==item.formId:
                try:
                    oldFile=open("%s/%s.json"%(formPath,old['formId']),"rb")
                    newFile=open('%s/%s.json'%(formPath,item.formId),"wb")
                    newFile.write(oldFile.read())
                    newFile.close()
                    oldFile.close()
                    os.remove("%s/%s.json"%(formPath,old['formId']))
                except Exception:
                    pass
        item.save()
        return toDict(item)
    def queryHtml(self):
        page = getPage(self.request)
        limit = getLimit(page)
        retBean=Html.objects.filter(type=self.getByKey("type"))
        return {'rows':convertToArray(retBean[limit.get("start"):limit.get("end")].values())}
    def treeForm(self):
        return self.toHtml("treeForm")
    
    def queryForm(self):
        modId = self.request.GET.get("id")
        item=Html.objects.get(id=modId)
        try:
            file=open(formPath+item.formId+".json","rb")
            retBean= {'form':file.read()} 
            file.close()
        except Exception:
            retBean={'form':None} 
        return retBean
    def getComp(self):
        
        key = self.request.POST.get("key")
        item=self.request.POST.get("item")
        item=json.loads(item)
        itemPath="common/"+key+".html"
        if item.has_key("noescape") and item['noescape']:
            return  {"html":renderNoescape(itemPath,item)}
        else:
            return {"html":renderField(itemPath,item)}
    def getScript(self):
        script=self.request.POST.get("name")
        file=open(formPath+"/js/"+script,"rb")
        content=file.read()
        file.close()
        return {"script":content}
    def saveScript(self):
        script=self.getPost("script")
        form=Html.objects.get(id=self.getPost("id"))
        fileName=form['name']
        file=open(formPath+"/js/"+fileName+".js","wb")
        file.write(script); 
        file.close()
        return {"fileName":fileName+".js"}
        
    def preShow(self):
        content=self.getPost("json")
        log=JsonLog()
        log.content=content
        log.name='预览'
        log.save()
        return str(log.id)
    def openPre(self):
        item=JsonLog.objects.get(id=self.getByKey("id"))
        content=json.loads(item.content)
        htmlArr=[]
        htmlArr.append(getBase(content['head'],None,True))
        htmlArr.append("<body>")
        for t in content['rows']:
            if t.has_key('childs'):
                t['param']['content']=getChild(None,t['childs'])
                htmlArr.append(renderNoescape("common/"+t['fieldType']+".html",t['param']))
            else:
                htmlArr.append(getHtml("common/"+t['fieldType']+".html",t['param']))
                
        htmlArr.append("</body></html>")
        return "".join(htmlArr)   
         
    def queryField(self):
        sql="select formId as id,formId as text from db_html"
        return execMysql(sql)
    def saveJson(self):
        id=self.request.POST.get("id")
        content=self.request.POST.get("json")
        item=Html.objects.get(id=id)
        formFile=open(formPath+item.formId+".json","wb")
        formFile.write(content)
        formFile.close()
        log=JsonLog()
        log.content=content
        log.name=id+":"+formPath+item.formId+".json"
        log.save()
        return retSuccess("创建成功")
    
    def saveHtml(self):
        self.jsMap=[]
        item=Html.objects.get(id=self.getPost("id"))
        if item['type']=='text':
            return saveText(item)
        formFile=open(formPath+item.formId+".json","rb")
        validFile=open(formPath+item.formId+".valid","wb")
        formJson=json.loads(formFile.read())
        validArr={}
        htmlArr=[]
        if formJson['head']:
            htmlArr.append(getBase(formJson['head'],item['name'],False))
            htmlArr.append("<body>")
        for t in formJson['rows']:
            addValid(validArr,t['param'])
            if t.has_key('childs'):
                t['param']['content']=getChild(validArr,t['childs'])
                t['param']['noescape']=True
                htmlArr.append(htmlAndJs(self,"common/"+t['fieldType']+".html",t['param']))
            else:
                htmlArr.append(htmlAndJs(self,"common/"+t['fieldType']+".html",t['param']))
        jsFile=open(formPath+"/js/"+item['name']+"_temp.js","wb")
        jsFile.write("\n".join(self.jsMap)) 
        #验证信息打入到js文件中
        jsFile.write("var _valid_="+json.dumps(validArr)+";")
        jsFile.close()
        #写入表单文件  
        validFile.write(json.dumps(validArr))
        validFile.close() 
        htmlArr.append("</body></html>")
        htmlFile=open(formPath+"html/"+item.name+".html","wb")
        htmlFile.write("".join(htmlArr))
        htmlFile.close()
        formFile.close()
        return retSuccess("创建成功")

                
    def createJson(self, name, field):
        temp={}
        temp['head']={"name":"html头文件","id":"52","fieldType":"BaseHead1.0","param":{"name":"html头文件","pageTitle":"web","devModel":True}}
        temp['rows']=[]
        for item in field:
            temp['rows'].append({"fieldType":"Input1.0","id":2,"name":field[item],"param":{"id":item,"name":field[item]}})
        formFile=open(formPath+"db_"+name+"_form.json","wb")
        formFile.write(json.dumps(temp))
        formFile.close()
        form=Html()
        form.setAttr("name", "db_"+name)
        form.setAttr("rightId","db_"+name)
        form.setAttr("path","/db")
        form.setAttr("formId","db_"+name+"_form")
        form.setAttr("type","html")
        form.save()
    
def htmlAndJs(self,path,param):
    ret=getHtml(path,param)
    return getJs(self,ret)
def getJs(self,text):
    start=text.find("<script>")
    end=text.find("</script>")
    if start>-1:
        self.jsMap.append(text[start+8:end])
        return getJs(self,text[0:start]+text[end+9:len(text)])
    else:
        return text;
def getBase(t,name,preShow):
    #非预览需引入模板分离出的Js内容
    
    if not preShow:
        t['param']['noescape']=True
        t['param']['js']="<script src='./js/"+name+"_temp.js' type='text/javascript'></script>"
        return getHtml("common/"+t['fieldType']+".html",t['param'])
    else: 
        #预览清空 头采用base/head.html
        return getHtml("base/head.html",t['param'])
        
def getHtml(path,item):
    if item.has_key("noescape") and item['noescape']:
        return renderNoescape(path,item)
    else:
        return renderField(path,item)

def addValid(obj,t):
    if t and t['id']:
        obj[t['id']]={"id":t['id'],"name":t['name'],"noNull":t["noNull"],"errorMsg":t["errorMsg"],"valid":t["valid"]}
def getChild(valid,childs):
    htmlArr=[]
    for field in childs:
        if not valid==None:
            addValid(valid,field['param'])
        htmlArr.append(getHtml("common/"+field['fieldType']+".html",field['param'])) 
    return "".join(htmlArr)